package com.fanwei.afgorithm.code227;

import java.util.Stack;

/**
 * @author fanwei
 * @version 1.0.0
 * @ClassName BasicCalculator2.java
 * @Description 基本计算器 II
 * @createTime 2022年03月16日 07:56:00
 */
public class BasicCalculator2 {

    public static void main(String[] args) {
        BasicCalculator2.calculate(" 3+5 / 2 ");
    }

    public static int calculate(String s) {
        //去空格
        s = s.replace(" ","");
        char[] arr = s.toCharArray();
        if(arr.length == 0) return 0;
        Stack<Integer> stack = new Stack<>();
        //对每个字符串数字的的集
        int num = 0;
        //开头默认用+号来确认
        char sign = '+';
        //todo - 便利相关字符串成正负数到stack中存储
        for (int i = 0; i < arr.length; i++){
            char cls = arr[i];
            //判断是否是数字
            if (isNum(cls)){
                num = 10 * num + (cls - '0');
            }
            //假如是符号或者最后一位数字添加到stack中
            if (!isNum(cls)|| i == (arr.length-1)){
                //todo - 乘除计算逻辑放在放在stack的头，加减放在stack的底部
                //用于计算乘除的结果
                int pre;
                switch (sign){
                    case '+':
                        stack.push(num);
                        break;
                    case '-':
                        stack.push(-num);
                        break;
                    case '*':
                        //拿出头部
                        pre = stack.pop();
                        stack.push(num * pre);
                        break;
                    case '/':
                        //拿出头部
                        pre = stack.pop();
                        stack.push(pre / num);
                        break;
                }
                // 更新符号为当前符号，数字清零
                if (cls != ' ')sign = cls;
                num = 0;
                pre = 0;
            }

        }
        System.out.println(stack.toString());
        //将stack添加出来就是加减的总和
        int total = 0;
        while (!stack.isEmpty()){
            total += stack.pop();
        }
        // System.out.println(total);
        return total;
    }

    private static boolean isNum(char c){
        if (c >= '0' && c <= '9'){
            return true;
        }else {
            return false;
        }
    }
}
